import logging

import tornado
import json

from api_base import *


class APILoginHandler(APIBaseHandler):
    async def post(self):
        '''
        用户登录
        Content-Type:   json
        param:          username    用户名
        param:          password    密码(前端进行hash)
        return:         info        ok成功，err失败
        '''
        try:
            js = json.loads(self.request.body)
            username = js['username']
            password = js['password']
        except:
            self.write_json({'info': 'json_error'})
            return
        logging.info('username: {} password: {}'.format(
            username, password))
        doc = await self.db.users.find_one({'username': username, 'password': password})
        if doc:
            self.set_secure_cookie('user', username, expires_days=7)
            role = doc.get('role')
            self.set_secure_cookie(
                'role', (str(role) if role else '0'), expires_days=7)
            self.write_json({'info': 'ok'})
        else:
            self.write_json({'info': 'err'})


class APILogoutHandler(APIBaseHandler):
    @check_role(RoleStudent)
    def get(self):
        '''
        用户登出
        return:         info        ok成功
        '''
        self.clear_cookie('user')
        self.set_secure_cookie('role', '0')
        self.write_json({'info': 'ok'})


class APIRegisterHandler(APIBaseHandler):
    MUST_FIELDS = ['username', 'password']
    OPTIONAL_FIELDS = [('realname', ''), ('class', ''), ('uid', '')]

    async def get(self):
        '''
        用户是否存在
        param:      username    要判断的用户名
        return:     info        ok:不存在 user_exist:存在 err:错误
        '''
        try:
            username = self.get_argument('username')
            ret = await self.db.users.find_one({'username': username})
            if ret:
                self.write_json({'info': 'user_exist'})
            else:
                self.write_json({'info': 'ok'})
        except:
            self.write_json({'info': 'err'})

    async def post(self):
        '''
        用户注册
        '''
        try:
            js = json.loads(self.request.body)
            to_insert = {k: js[k] for k in self.MUST_FIELDS}
            to_insert.update(
                {k: js.get(k) or d for k, d in self.OPTIONAL_FIELDS})
            to_insert['role'] = RoleStudent  # Default Student
        except:
            self.write_json({'info': 'json_err'})
            return
        try:
            await self.db.users.insert_one(to_insert)
            self.write_json({'info': 'ok'})
        except:
            self.write_json({'info': 'user_exist'})
